package descentFly.app.radar
{
	import UIFree.ObjectEvent;
	import UIFree.uif_Timer;
	import UIFree.uif_component;
	import UIFree.uif_ecomponent;
	
	import descentFly.app.df_component;
	
	import flash.events.Event;
	import flash.geom.Matrix3D;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.geom.Vector3D;
	
	public class df_radarLayer extends df_component {
		private var _mask		: uif_ecomponent;
		private var _line		: df_line;	
		private var _timer		: uif_Timer;
		private var _step		: Number;
		private var _index		: int;
		private var _stepCount	: int;
		private var _points		: Array;
		private var _rlayer		: uif_ecomponent;
		public static var SCALE	: Number = 0.02;
		
		public function df_radarLayer(parent: df_radarMonitor, styleClass:Object) {
			var rect: Rectangle = parent.getInner();
			super(parent, rect.x, rect.y, rect.width, rect.height, styleClass);
			
			rect = getInner();
			_mask = new uif_ecomponent(this, rect.x, rect.y, rect.width, rect.height, {
				fill_color	: 0xFFFFFF,
				fill_alpha	: 1,
				rounds		: style.rounds
			});
			
			_rlayer = new uif_ecomponent(this, 0, 0, width, height);
			_rlayer.mask = _mask;
			
			new df_grid(_rlayer, rect.x, rect.y, rect.width, rect.height, {
				line_width	: style.line_width,
				line_color  : style.line_color,
				line_alpha	: style.line_alpha
			});
			
			_line = new df_line(_rlayer, style.line);
			_line.x = rect.x + (rect.width + _line.getSpace(true)) / 2;
			_line.y = rect.y + (rect.height + _line.getSpace(true)) / 2;
			
			_timer = new uif_Timer(50, doTimer);
			_timer.start();
			_stepCount = 20;
			
			_step 	= 360 / _stepCount;
			_index	= 0;
			_points = new Array(_stepCount);
			
			for (var i:int=0; i<_points.length; i++)
				_points[i] = new Array();
		}
		
		protected function doTimer(e: Event): void {
			if (!Space || !Space.disableScene) {
				var matrix: Matrix3D = new Matrix3D();
				matrix.appendRotation(-_line.rotation, Vector3D.Y_AXIS);
				
				var event: df_radarEvent = new df_radarEvent(df_radarEvent.GETPOINTS, {
					list	: new Array(),
					direct	: matrix.transformVector(Vector3D.X_AXIS),
					angle	: _step
				});
				stage.dispatchEvent(event);
				refreshPoints(_index, event);
				
				_index = (_index + 1) % _stepCount;
				_line.rotation = -(_index * _step);
			}
		}
		
		protected function refreshPoints(a_sector: int, e: df_radarEvent): void {
			var v_center: Point = this.center;
			_points[a_sector].forEach(function(point: df_point, i: int, arr: Array): void {
				point.dispose();
			});
			_points[a_sector].splice(0);
			e.list.forEach(function(item: Object, i: int, arr: Array): void {
				var point: Vector3D = item.point;
				_points[a_sector].push(new df_point(_rlayer, v_center.x + point.x * SCALE, 
												v_center.y - point.z * SCALE, style['point' + item.type]));
			});
		}
	}
}